<template>
  <div class="p-2">
    <!-- 返回按钮 -->
    <!-- <div class="mb-[10px]">
      <el-button type="primary" icon="Back" @click="handleBack">返回</el-button>
    </div> -->

    <!-- 搜索区域 -->
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
            <el-form-item label="楼宇名称">
              <el-select v-model="queryParams.housingId" placeholder="请搜索楼宇" clearable filterable :disabled="housingIdTypeFlag">
                <el-option v-for="item in buildingList" :key="item.id" :label="item.housingName" :value="item.id" />
              </el-select>
            </el-form-item>

            <el-form-item label="房间名称">
              <el-input v-model="queryParams.houseName" placeholder="请输入房间名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="面积" prop="area">
              <el-input-number
                v-model="queryParams.minArea"
                placeholder="最小面积"
                :min="0"
                :precision="2"
                houseName
                :controls="false"
                style="width: 120px"
                clearable
              />
              <span class="mx-2">-</span>
              <el-input-number
                v-model="queryParams.maxArea"
                placeholder="最大面积"
                clearable
                :min="0"
                :precision="2"
                :controls="false"
                style="width: 120px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <!-- <el-button icon="Refresh" @click="resetQuery">重置</el-button> -->
              <el-button type="warning" icon="Plus" @click="handleAdd">新增</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <!-- 列表区域 -->
    <el-card shadow="hover">
      <el-table v-loading="loading" border :data="roomList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="楼宇名称" prop="housingName" width="260" align="center" />
        <el-table-column label="房间名称" prop="houseName" width="260" align="center" />
        <el-table-column label="所在楼层" prop="floorName" width="260" align="center" />
        <el-table-column label="房间面积(㎡)" prop="houseArea" width="160" align="center" />
        <!-- <el-table-column label="地址" prop="address" width="260" align="center" /> -->
        <el-table-column label="备注" prop="remark" width="260" align="center" />
        <el-table-column label="创建时间" prop="createTime" align="center" width="160" />
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" link icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="danger" link icon="Delete" @click="handleDelete(scope.row)" v-if="roleSetting === 'admin'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>

    <!-- 新增/修改对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="roomFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="楼宇名称" prop="housingId">
          <el-select v-model="form.housingId" placeholder="请搜索楼宇" filterable :disabled="housingIdTypeFlag" @change="handleBuildingChange">
            <el-option v-for="item in buildingList" :key="item.id" :label="item.housingName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="房间名称" prop="houseName">
          <el-input v-model="form.houseName" placeholder="请输入房间名称" />
        </el-form-item>
        <el-form-item label="选择楼层" prop="floor">
          <el-select v-model="form.floor" placeholder="请选择楼层" clearable filterable>
            <el-option v-for="item in levelList" :key="item.id" :label="item.floorName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="面积(㎡)" prop="houseArea">
          <el-input-number v-model="form.houseArea" placeholder="请输入面积" :min="0" :precision="2" style="width: 100%" />
        </el-form-item>
        <!-- <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入房间名称" />
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="RoomList">
import { ref, getCurrentInstance, ComponentInternalInstance, onMounted } from 'vue';

//HousingDetails
import {
  getBuildingList,
  listHousingDetails,
  getParkFloor,
  addHousingDetails,
  updateHousingDetails,
  removeHousingDetails
} from '@/api/system/building';
import type { FormInstance } from 'element-plus';
import { useRoute } from 'vue-router';

const route = useRoute();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const roleSetting = ref(localStorage.getItem('username'));
// 数据列表
const roomList = ref<any[]>([]);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref<string[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');
const open = ref(false);

// 表单引用
const roomFormRef = ref<FormInstance>();

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  housingId: '',
  houseName: '',
  minArea: undefined,
  maxArea: undefined
});

// 表单数据
const form = ref({
  id: undefined,
  housingId: '',
  houseName: '',
  houseArea: '',
  address: '',
  remark: ''
});

const levelList = ref<any>([]);

// 表单验证规则
const rules = ref({
  houseName: [{ required: true, message: '房间名称不能为空', trigger: 'blur' }],
  houseArea: [{ required: true, message: '面积不能为空', trigger: 'blur' }],
  floor: [{ required: true, message: '请选择楼层', trigger: 'blur' }]
});

const buildingList = ref<any>([]);
/** 查询楼宇列表 */

const fetchBuildingList = async () => {
  // loading.value = true;
  try {
    const res = await getBuildingList({ pageNum: 1, pageSize: 100 });
    buildingList.value = res.rows;
  } finally {
    // loading.value = false;
  }
};

/** 查询房间列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listHousingDetails(queryParams.value);
    roomList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    housingId: '',
    houseName: '',
    minArea: undefined,
    maxArea: undefined
  };
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  title.value = '新增房间';
  form.value.housingId = queryParams.value.housingId;
  open.value = true;
};

/** 修改按钮操作 */
const handleUpdate = (row: any) => {
  reset();

  form.value = { ...row };

  title.value = '修改房间';
  handleBuildingChange();
  open.value = true;
};

/** 删除按钮操作 */
const handleDelete = async (row?: any) => {
  const buildingIds = row?.id || ids.value;
  await proxy?.$modal.confirm(`是否确认删除选中的数据？`);
  await removeHousingDetails(buildingIds);
  proxy?.$modal.msgSuccess('删除成功');
  getList();
};

/** 提交按钮 */
const submitForm = () => {
  roomFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (form.value.id) {
        await updateHousingDetails(form.value);
        proxy?.$modal.msgSuccess('修改成功');
      } else {
        await addHousingDetails(form.value);
        proxy?.$modal.msgSuccess('新增成功');
      }
      open.value = false;
      getList();
    }
  });
};

/** 取消按钮 */
const cancel = () => {
  open.value = false;
  reset();
};

/** 表单重置 */
const reset = () => {
  form.value = {
    id: undefined,
    houseName: '',
    houseArea: 0,
    floor: '',
    remark: ''
  };
  roomFormRef.value?.resetFields();
};
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 返回按钮操作 */
// const handleBack = () => {
//   proxy?.$router.back();
// };
const housingIdTypeFlag = ref(false);
/** 搜索按钮操作 */
const getPara = () => {
  queryParams.value.housingId = Number(route.query.buildingId) || '';
  if (queryParams.value.housingId != '') {
    housingIdTypeFlag.value = true;
  } else {
    housingIdTypeFlag.value = false;
  }
  queryParams.value.pageNum = 1;
  getList();
};

onMounted(() => {
  getPara();
  getList();
  console.log('buildingList====');
  fetchBuildingList();
});

const handleBuildingChange = async () => {
  // console.log('form.value.housingId', form.value.housingId);
  // if (form.value.housingId) {
  //   // 根据housingId筛选房间并提取唯一楼层
  //   const filteredRooms = buildingList.value.filter((room) => room.id === form.value.housingId);
  //   console.log('filteredRooms', filteredRooms);
  //   const floors = filteredRooms.map((room) => room.floor);
  //   const maxFloor = Math.max(...floors) || 0;
  //   levelList.value = [];
  //   for (let num = 1; num <= maxFloor; num++) {
  //     levelList.value.push({
  //       label: `楼层 ${num}`,
  //       value: num
  //     });
  //   }
  // } else {
  //   levelList.value = [];
  // }
  levelList.value = [];
  const res = await getParkFloor({ housingId: form.value.housingId });
  if (res.code === 200) {
    levelList.value = res.data;
  }
};
</script>
